package com.zkx.fssb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zkx.fssb.constant.ResolveDatabaseTableIdSelfGrowingFailureConstant;
import com.zkx.fssb.context.BaseContext;
import com.zkx.fssb.domain.dto.CartDto;
import com.zkx.fssb.domain.po.Cart;
import com.zkx.fssb.mapper.CartMapper;
import com.zkx.fssb.service.CartService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart>implements CartService {




    @Override
    public List<Cart> getCartListByUserId(Integer userId) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId!=null,Cart::getUserId, userId);

        List<Cart> cartList = this.getBaseMapper().selectList(wrapper);
        return cartList;
    }

    @Override
    public void saveCustomCart(CartDto cartDto) {
        Cart cart = new Cart();
        BeanUtils.copyProperties(cartDto,cart);
        cart.setUserId(1);
        List<Cart> cartList = this.getCartListByUserIdAndName(cart);
        if (cartList.size() > 0){
            //上面的动态条件查询永远只会查出一条数据
            Cart c = cartList.get(0);
            //如果已经存在了，只需要将数量加一
            c.setCartNumber(c.getCartNumber() + cartDto.getCartNumber());
            c.setCartAmount(c.getCartNumber() * cartDto.getCartAmount());

            this.updateById(c);
        }else {
            //如果不存在，需要插入一条购物车数据

            cart.setUserId(1);
            cart.setCartNumber(1);
            cart.setCreateTime(LocalDateTime.now());
            this.save(cart);
        }



    }

    @Override
    public void deleteCartByUserId(CartDto cartDto) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(cartDto.getUserId()!=null,Cart::getUserId,cartDto.getUserId())
                .eq(cartDto.getCartId()!=null,Cart::getCartId,cartDto.getCartId());

        this.getBaseMapper().delete(wrapper);

        


    }

    @Override
    public List<Cart> getCartListByUserIdAndName(Cart cart) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(cart.getUserId()!=null,Cart::getUserId, cart.getUserId())
                .eq(cart.getCartName()!=null,Cart::getCartName,cart.getCartName());

        List<Cart> cartList = this.getBaseMapper().selectList(wrapper);
        return cartList;



    }
}
